package src.itheima05;

import java.util.Arrays;

/*
    冒泡排序:
        1.原理: 每次都从第一个元素(索引0),向后两两比较,只要前面的元素大于后面的元素,就交换
        2.总结:
            (1) 5个数,需要排4趟,n个数,需要排n-1趟
            (2)每趟排序的次数,比上一趟少1次
            (3)规律:

            	第一趟			 第二趟			 第三趟      第四趟
                [0] vs [1]		[0] vs [1]		[0] vs [1]	[0] vs [1]
                [1] vs [2]		[1] vs [2]		[1] vs [2]
                [2] vs [3]		[2] vs [3]
                [3] vs [4]


 */
public class Demo05BubbleSort {
    public static void main(String[] args) {
        int[] arr = {7,6,5,4,3};
        System.out.println("第一趟排序前: "+ Arrays.toString(arr));//[7, 6, 5, 4, 3]

        /*
            第一趟
            [0] vs [0+1]
            [1] vs [1+1]
            [2] vs [2+1]
            [3] vs [3+1]
         */
        for(int j = 0;j<4-0;j++) {
            if(arr[j] > arr[j+1]) {
                //交换数组元素
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }

        System.out.println("第一趟排序后: "+ Arrays.toString(arr));//[6, 5, 4, 3, 7]

        /*
            第二趟
            [0] vs [0+1]
            [1] vs [1+1]
            [2] vs [2+1]
         */

        for(int j = 0;j<4-1;j++) {
            if(arr[j] > arr[j+1]) {
                //交换数组元素
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }

        System.out.println("第二趟排序后: "+ Arrays.toString(arr));//[5, 4, 3, 6, 7]
        /*
            第三趟
            [0] vs [0+1]
            [1] vs [1+1]

         */
        for(int j = 0;j<4-2;j++) {
            if(arr[j] > arr[j+1]) {
                //交换数组元素
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }

        System.out.println("第三趟排序后: "+ Arrays.toString(arr));//[4, 3, 5, 6, 7]

        /*
            第四趟
            [0] vs [0+1]

         */
        for(int j = 0;j<4-3;j++) {
            if(arr[j] > arr[j+1]) {
                //交换数组元素
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }

        System.out.println("第四趟排序后: "+ Arrays.toString(arr));//[3, 4, 5, 6, 7]

 /*       for (int i=0;i<10; i++){
            if(arr[i]>arr[i+1]){
                int a=arr[i+1];
                arr[i]=arr[i+1];
                arr[i]=a;
            }
        }*/
    }


}
